from rest_framework.viewsets import ModelViewSet
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.authentication import TokenAuthentication
from apps.common.base.models import BaseModel
from apps.common.base.serializers import BaseSerializer
from apps.common.base.dao import BaseDao
from apps.common.utils.response import *
from apps.common.utils.fileHeader import *
from apps.common.utils.tools import *
from decimal import Decimal
import requests
import datetime
import os
import xlwt
import xlrd


class BaseViewSet(ModelViewSet):

    DAO_CLASS = BaseDao
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]

    @action(methods=['post'], detail=False)
    def createAction(self, request):
        params = getRequestParams(self.request)
        self.DAO_CLASS().create(params)
        return Response(response_success('新增成功'))

    @action(methods=['post'], detail=False)
    def updateAction(self, request):
        params = getRequestParams(self.request)
        obj_id = params.get('obj_id')
        if isEmptyStr(obj_id):
            return Response(response_message('obj_id参数必填'))
        self.DAO_CLASS().update(obj_id, params)
        return Response(response_success('更新成功'))

    @action(methods=['post'], detail=False)
    def deleteAction(self, request):
        params = getRequestParams(self.request)
        obj_ids = params.get('obj_ids')
        if type(obj_ids) != list:
            return Response(response_message('obj_ids应为数组类型'))
        self.DAO_CLASS().delete(obj_ids, params)
        return Response(response_success('删除成功'))

    @action(methods=['post'], detail=False)
    def getItemById(self, request):
        params = getRequestParams(self.request)
        obj_id = params.get('obj_id')
        if not obj_id:
            return Response(response_message('obj_id参数必填'))
        obj = self.DAO_CLASS().findOneByObjId(obj_id)
        model = self.serializer_class(obj).data
        return Response(response_success(model))